package com.mengniu.commerce.sync.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mengniu.commerce.common.core.domain.R;
import com.mengniu.commerce.common.core.enums.ModuleEnum;
import com.mengniu.commerce.common.core.utils.StringUtils;
import com.mengniu.commerce.common.template.enums.APIUrlEnum;
import com.mengniu.commerce.sync.api.base.MnResult;
import com.mengniu.commerce.sync.api.domain.PointsIncreaseModel;
import com.mengniu.commerce.sync.api.domain.PointsReduceModel;
import com.mengniu.commerce.sync.api.dto.RetryDTO;
import com.mengniu.commerce.sync.common.constant.CodeConstants;
import com.mengniu.commerce.sync.common.utils.MnResultUtil;
import com.mengniu.commerce.sync.common.utils.RestTemplateUtil;
import com.mengniu.commerce.sync.exception.RetryException;
import com.mengniu.commerce.sync.service.PointsService;
import com.mengniu.commerce.sync.utils.RetryUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.retry.RetryContext;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.retry.support.RetrySynchronizationManager;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * 会员积分相关实现类
 */
@Service
@Slf4j
public class PointsServiceImpl implements PointsService {

    public static final String baseURL = "https://t-openapi-gateway.mengniu.cn/";
    @Resource
    private RestTemplateUtil restTemplateUtil;

    @Resource
    private RetryUtils retryUtils;
    /**
     * 减少积分
     */
    @Override
    @Retryable(value = { RetryException.class }, maxAttempts = 8, backoff = @Backoff(delay = 10000))
    public R pointsReduce(PointsReduceModel pointsReduceModel, RetryDTO retryDTO) {
        log.info("用户减少积分入参{}", JSONObject.toJSONString(pointsReduceModel));
        RetryContext context = RetrySynchronizationManager.getContext();
        log.info("当前减少积分重试次数{}",JSONObject.toJSONString(context));
        JSONObject param = (JSONObject) JSON.toJSON(pointsReduceModel);
        log.info("调用蒙牛用户减少积分参数为{}",JSONObject.toJSONString(param));
        JSONObject result = new JSONObject();
        try{
            result = restTemplateUtil.doPost(param, baseURL + APIUrlEnum.POINTS_REDUCE.getPath());
            log.info("调用蒙牛用户减少积分响应为{}",JSONObject.toJSONString(result));
        }catch (Exception e){
            log.error("调用蒙牛用户减少积分接口失败",e);
            Long id = retryUtils.insertOrUpdate(param, retryDTO.getSource(), retryDTO.getStoreName(), ModuleEnum.POINTS.getModuleName(), APIUrlEnum.POINTS_REDUCE.getMethod(), context.getRetryCount(), e.getMessage(),retryDTO.getRetryId());
            retryDTO.setRetryId(id);
            throw new RetryException("发生了重试异常{}", e);
        }
        if (result == null || ! result.getInteger("code").equals(CodeConstants.SUCCESS_CODE)){
            return R.fail(result,"调用蒙牛接口失败");
        }
        return R.fail(result,"调用蒙牛接口失败");
    }

    /**
     *增加积分
     */
    @Override
    @Retryable(value = { RetryException.class }, maxAttempts = 8, backoff = @Backoff(delay = 10000))
    public  R pointsIncrease(PointsIncreaseModel pointsIncreaseModel, RetryDTO retryDTO) {
        log.info("用户增加积分入参{}", JSONObject.toJSONString(pointsIncreaseModel));
        RetryContext context = RetrySynchronizationManager.getContext();
        log.info("当前增加积分重试次数{}",JSONObject.toJSONString(context));
        JSONObject param = (JSONObject) JSON.toJSON(pointsIncreaseModel);
        log.info("调用蒙牛用户增加积分参数为{}",JSONObject.toJSONString(param));
        JSONObject result = new JSONObject();
        try{
            result = restTemplateUtil.doPost(param, baseURL + APIUrlEnum.POINTS_INCREASE.getPath());
            log.info("调用蒙牛用户增加积分响应为{}",JSONObject.toJSONString(result));
        }catch (Exception e){
            log.error("调用蒙牛用户增加积分接口失败",e);
            Long id = retryUtils.insertOrUpdate(param, retryDTO.getSource(), retryDTO.getStoreName(), ModuleEnum.POINTS.getModuleName(), APIUrlEnum.POINTS_INCREASE.getMethod(), context.getRetryCount(), e.getMessage(),retryDTO.getRetryId());
            retryDTO.setRetryId(id);
            throw new RetryException("发生了重试异常{}", e);
        }
        if (result == null || ! result.getInteger("code").equals(CodeConstants.SUCCESS_CODE)){
            return R.fail(result,"调用蒙牛接口失败");
        }
        return R.fail(result,"调用蒙牛接口失败");
    }
}
